import { useState, useReducer } from "react";
import "./App.css";

function App() {
  // const [count, setCount] = useState(0)

  const initData = [
    { name: "小满(只)", price: 100, count: 1, id: 1, isEdit: false },
    { name: "中满(只)", price: 200, count: 2, id: 2, isEdit: false },
    { name: "大满(只)", price: 300, count: 1, id: 3, isEdit: false },
  ];

  type List = typeof initData;
  type Action = {
    type: "add" | "del" | "edit" | "update_name",
    id: number,
    newName?: string
  }

  const initDataFn = (state: List) => {
    return state
  };
  function Reducer(state: List, action: Action) {
    const itemIndex = state.findIndex(item => item.id == action.id)
    if (itemIndex === -1) return state;
    const item = state[itemIndex];

    switch (action.type) {
      case "add":
        const newItem = { ...item, count: item.count + 1 };
        return [...state.slice(0,itemIndex),newItem,...state.slice(itemIndex+1)];
      case "del":
        const newItem2 = { ...item, count: item.count - 1 };
        return [...state.slice(0,itemIndex),newItem2,...state.slice(itemIndex+1)];
      case "edit":
        item.isEdit = !item.isEdit;
        const newItem3 = { ...item, isEdit: !item.isEdit };
        return [...state.slice(0,itemIndex),newItem3,...state.slice(itemIndex+1)]
      case "update_name":
        const newItem4 = { ...item, name: action.newName! };
        return [...state.slice(0,itemIndex),newItem4,...state.slice(itemIndex+1)]
      default:
        return state;
    }

  }

  const [state, dispatch] = useReducer(Reducer, initData, initDataFn);

  return (
    <>
      <table border={1} cellPadding={10} cellSpacing={0} >
        <thead>
          <tr>
            <th>物品</th>
            <th>价格</th>
            <th>数量</th>
            <th>操作</th>
          </tr>
        </thead>
        <tbody>
          {state.map(item =>{
            return (
              <tr key={item.id}>
                <td>{item.isEdit?<input type="text" value={item.name} onBlur={_=>dispatch({ type: "edit", id: item.id })} onChange={e => dispatch({type: "update_name",id: item.id,newName:e.target.value})} />:<span>{item.name}</span>}</td>
                <td>{item.count * item.price}</td>
                <td>{item.count}</td>
                <td>
                  <button onClick={() => dispatch({type: 'edit', id: item.id})}>编辑</button>
                  <button onClick={() => dispatch({type: 'add', id: item.id})}>增加</button>
                  <button onClick={() => dispatch({type: 'del', id: item.id})}>删除</button>
                </td>
              </tr>
            )
          })}
        </tbody>
      </table>
    </>
  );
}

export default App;
